const { Client } = require('@elastic/elasticsearch')

const client = new Client({
    node: 'http://localhost:9200',
    maxRetries: 5,
    requestTimeout: 60000,
    sniffOnStart: true
})

export async function createIndex(docType: string, id: string, doc_json: any) {
    await client.index({
        index: docType,
        // type: '_doc', // uncomment this line if you are using Elasticsearch ≤ 6
        body: {
            title: doc_json.title,
            text: doc_json.text,
            docid: id
        }
    })
    await client.indices.refresh({ index: docType })
}

export async function deleteDoc(docType: string, id: string) {
    console.log(docType,id)
    await client.deleteByQuery({
        index: docType,
        body: {
            query: {
                match: {
                    docid: id
                }
            }
        }
    })
}

export async function run() {
    const { body } = await client.search({
        index: 'test',
        // type: '_doc', // uncomment this line if you are using Elasticsearch ≤ 6
        body: {
            query: {
                "multi_match": {
                    "query": "做空",
                    "type": "most_fields",
                    "fields": ["title", "text"]
                }
            }
        }
    })

    console.log(body.hits.hits)
}

export async function findIndex(docType: string, findStr: string) {
    const { body } = await client.search({
        index: docType,
        // type: '_doc', // uncomment this line if you are using Elasticsearch ≤ 6
        body: {
            query: {
                "multi_match": {
                    "query": findStr,
                    "type": "most_fields",
                    "fields": ["title", "text"]
                }
            }
        }
    })
    return body.hits.hits;
}